package com.bbs.controller;

import com.bbs.entity.Post;
import com.bbs.entity.User;
import com.bbs.service.PostService;
import com.bbs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class ProfileController {
    @Autowired
    private UserService userService;
    @Autowired
    private PostService postService;
    //个人主页
    @RequestMapping("/toMyProfile")
    public String profile(HttpSession session, Model model){
        int uid = (int) session.getAttribute("uid");//获取userid
        User user = userService.selectUser(uid);//通过userid获取user信息
        model.addAttribute(user);
        model.addAttribute(postService.selectUserPost(uid));
        return "myProfile";
    }

    @RequestMapping("/toEditProfile")
    public String EditProfile(HttpSession session,Model model){
        int uid = (int) session.getAttribute("uid");//获取userid
//        userService.updateUser(id);//通过userid获取user信息
        User user=userService.xinxiuser(uid);
        model.addAttribute("user",user);
        return "editProfile";
    }

    @RequestMapping("/editProfile")
    public String editProfile(User user,HttpSession session){
        int uid=(int)session.getAttribute("uid");
        user.setId(uid);
        userService.updateUser(user);
        return "redirect:/toMyProfile";
    }

    //查看别人主页
    @RequestMapping("/toProfile.do")
    public String toProfile(int uid,Model model,HttpSession session){
        Integer sessionUid=(Integer)session.getAttribute("uid");
        if(sessionUid!=null && sessionUid==uid){
            return "forward:/toMyProfile";
        }
        User user = userService.selectUser(uid);
        List<Post> postList = postService.selectUserPost(uid);

        model.addAttribute("user", user);
        model.addAttribute("postList", postList);
        return "profile";
    }
}
